package com.zzyl.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstants;
import com.zzyl.entity.AlertRule;
import com.zzyl.entity.DeviceData;
import com.zzyl.mapper.AlarmRuleMapper;
import com.zzyl.service.AlarmRuleService;
import com.zzyl.vo.DeviceDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AlertJob {

    @Autowired
    private AlarmRuleMapper alarmRuleMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private AlarmRuleService alarmRuleService;

    @Scheduled(cron = "0 * * * * ?")
    public void alertJob(){
        //1.查询所有的规则
        List<AlertRule> alertRuleList = alarmRuleMapper.queryAlarm(null, null, null);
        if (CollUtil.isEmpty(alertRuleList)){
            return;
        }


        //2.如果有规则，从redis中查
        List<Object> values = stringRedisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA_KEY);
        //3.非空判断
        if (CollUtil.isEmpty(values)){
            return;
        }

        //如果有数据就转换
        List<DeviceDataVo> allDataList = new ArrayList<>();
        values.stream().forEach(val ->{
            String json = (String) val;
            allDataList.addAll(JSONUtil.toList(json,DeviceDataVo.class));
        });

        //遍历每一条数据进行校验
       /* allDataList.stream().forEach(vo ->{
            alarmRuleService.alertFilter(vo);
        });*/
        allDataList.stream().forEach(vo ->{
            alarmRuleService.alertFilter(vo);;
        });

    }
}
